package firear.tvutils.ws.serv.req;


import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import firear.tvutils.ws.Constants;
import firear.tvutils.ws.serv.support.Progress;
import firear.tvutils.ws.serv.view.ViewFactory;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;



public class HttpHomeHandler implements HttpRequestHandler {
    @Override
    public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {



        String target = URLDecoder.decode(httpRequest.getRequestLine().getUri(), Constants.Config.ENCODING);
        HttpEntity entity = null;
        String contentType = "text/html;charset=" + Constants.Config.ENCODING;

        if(target.startsWith("/css/") || target.startsWith("/js/")){
            target = Constants.Config.SERV_ROOT_DIR + target;
            File file = new File(target);

            if (!file.exists()) { // 不存在
                httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND);
                entity = ViewFactory.getSingleton().renderTemp(httpRequest, "404.html");
            } else if (file.canRead()) { // 可读
                httpResponse.setStatusCode(HttpStatus.SC_OK);
                entity = ViewFactory.getSingleton().renderFile(httpRequest, file);
                contentType = entity.getContentType().getValue();
            } else { // 不可读
                httpResponse.setStatusCode(HttpStatus.SC_FORBIDDEN);
                entity = ViewFactory.getSingleton().renderTemp(httpRequest, "403.html");
            }
        }else if(target.equals("/")){
            httpResponse.setStatusCode(HttpStatus.SC_OK);
            entity = ViewFactory.getSingleton().renderTemp(httpRequest, "home.html");
        }else{
            httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND);
            entity = ViewFactory.getSingleton().renderTemp(httpRequest, "404.html");
        }


        httpResponse.setHeader("Content-Type", contentType);
        httpResponse.setEntity(entity);

        Progress.clear();

    }
}
